package com.dennis.nio;

import com.dennis.jedis.RedisPool;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import redis.clients.jedis.Jedis;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.dennis.client.SocketClient.nums;

/**
 * @author Dennis Li
 * @date 2020/8/19 21:56
 */
public class NioClient {

    private static final LongAdder times = new LongAdder();

    private static final CountHandler counter = new CountHandler();

    public static void count(String host, int port) {
        NioEventLoopGroup worker = new NioEventLoopGroup(1);
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(worker)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringDecoder(StandardCharsets.UTF_8));
                            pipeline.addLast(new StringEncoder(StandardCharsets.UTF_8));
                            pipeline.addLast(counter);
                        }
                    });
            bootstrap.connect(host, port).channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
        }
    }

    public static void client(String host, int[] ports) {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(worker)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringDecoder(StandardCharsets.UTF_8));
                            pipeline.addLast(new StringEncoder(StandardCharsets.UTF_8));
                            pipeline.addLast(new ClientHandler());
                        }
                    });

            final List<ChannelFuture> futures = Arrays.stream(ports)
                    .mapToObj(port -> bootstrap.connect(host, port))
                    .collect(Collectors.toList());

            futures.forEach(future -> {
                try {
                    future.channel().closeFuture().sync();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        } finally {
            worker.shutdownGracefully();
        }
    }

    public static void main(String[] args) {

        final ExecutorService pool = Executors.newSingleThreadExecutor();
        final ExecutorService redisCollect = Executors.newSingleThreadExecutor();

        final int threads = nums;

        final int[] ports = IntStream.range(6001, 6000 + threads).toArray();

        redisCollect.submit(() -> {
                    final Jedis redis = RedisPool.pool.getResource();
                    redis.select(5);
                    try {
//                        while (counter.getCount() < 100) {
//                            Thread.sleep(100);
//                        }
                        for (int i = 0; i < 3000; i++) {
                            Thread.sleep(100);
                            redis.set("netty:" + threads + ":" + i, Integer.toString(counter.getCount()));
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
        );
        pool.submit(() -> client("localhost", ports));
        count("localhost", 6000);
    }

}
